﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace PacoToolKit.Xml
{
    /// <summary>
    /// Linq方式的Xml帮助类
    /// </summary>
    public class LinqXml
    {
        /// <summary>
        /// 查询根元素
        /// </summary>
        /// <param name="url"></param>
        /// <param name="elementName"></param>
        /// <returns></returns>
        public static IEnumerable<XElement> GetRootElements(string url, string elementName)
        {
            XDocument doc = XDocument.Load(url);
            IEnumerable<XElement> elements = from e in doc.Elements(elementName) select e;
            return elements;
        }

        /// <summary>
        /// 查询子元素
        /// </summary>
        /// <param name="url"></param>
        /// <param name="rootName"></param>
        /// <param name="elementName"></param>
        /// <returns></returns>
        public static IEnumerable<XElement> GetSonElements(string url, string rootName, string elementName)
        {
            XDocument doc = XDocument.Load(url);
            var query = from p in doc.Element(rootName).Elements(elementName)
                        select p;
            return query;
        }

        /// <summary>
        /// 查询子孙元素
        /// </summary>
        /// <param name="url"></param>
        /// <param name="elementName"></param>
        /// <returns></returns>
        public static IEnumerable<XElement> GetAllChildrenElements(string url,string elementName)
        {
            XElement root = XElement.Load(url);
            var query = from b in root.Descendants(elementName) //Descendants轴方法与Elements类型，不过Elements只查找当前元素下的直接子节点，而Descendants则会遍历当前元素下任意层级的子元素。
                        select b;
            return query;
        }

        /// <summary>
        /// 查询元素中符合name的元素的值
        /// </summary>
        /// <param name="elements"></param>
        /// <param name="elementName"></param>
        /// <returns></returns>
        public static string QueryElementValue(IEnumerable<XElement> elements,string elementName)
        {
            var match = elements.Where(x => x.Name==elementName).ToList();
            if (match.Count == 0)
                return string.Empty;
            else
                return match.First().Value;
        }

        /// <summary>
        /// 查询一个元素中符合name的第一个子元素的值
        /// </summary>
        /// <param name="ele"></param>
        /// <param name="elementName"></param>
        /// <returns></returns>
        public static string QueryElementValue(XElement ele,string elementName)
        {
            return ele.Element(elementName).Value;
        }
    }
}
